package com.fzrskj.cloud.free.user.service;

import com.fzrskj.cloud.free.core.WiniisCacheImplMain;
import com.fzrskj.cloud.free.core.tool.CSessionTool;
import com.fzrskj.cloud.free.user.utils.ProductTokenUtils;
import com.winiis.component.cache.core.CacheUtils;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.tool.JsonTool;
import ms.core.tool.StrTool;
import ms.core.tool.XmlCodeParser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * VncTestService.
 *
 * @author zj.
 *         Created on 2018/11/20 0020.
 */
public class ProductTokenService extends CObject {

    /**
     * 产品生成Token-用于第三登录回来取数据
     */
    public String createToken(HttpServletRequest request, HttpServletResponse response, String p, String sid) {
        int uid = CSessionTool.getUidCloud(sid);
        if (uid <= 0) {
            return XmlCodeParser.formatResultTips(false, SysErr.USER_NOT_LOGIN);
        }

        //参数获取
        String productClass = JsonTool.getStrValue(p, "productClass", "");
        String instance = JsonTool.getStrValue(p, "instance", "");
        if (StrTool.isBlankStr(productClass) || StrTool.isBlankStr(instance)){
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        //组合数据.
        ProductTokenUtils pUtils = new ProductTokenUtils();
        String token = pUtils.CreateToken(productClass, instance);
        if (!SysErr.CODE_SUCCESS.equals(pUtils.getErrCode())){
            return XmlCodeParser.formatResultTips(false, pUtils.getErrCode());
        }
        if (StrTool.isBlankStr(token)){
            return XmlCodeParser.formatResultTips(false, pUtils.getErrCode(), "生成Token失败,请联系管理员");
        }

        return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, token);
    }

    /**
     * 验证Token-用于第三登录回来取数据.
     */
    public String checkToken(HttpServletRequest request, HttpServletResponse response, String p, String sid) {
        //参数获取
        String token = JsonTool.getStrValue(p, "token", "");

        if (StrTool.isBlankStr(token)){
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_PARAM_ERR);
        }

        //取出缓存数据.
        CacheUtils cacheUtils = new CacheUtils(new WiniisCacheImplMain());
        String cacheData = cacheUtils.get(token);
        cacheUtils.delete(token);
        if (cacheData == null){
            return XmlCodeParser.formatResultTips(false, SysErr.SYS_DATA_NOT_FOUND, "无效的Token");
        }

        return XmlCodeParser.formatResultData(true, SysErr.CODE_SUCCESS, cacheData);
    }
}
